<template>
  <div :id="pointId" class="textarea" tabindex="0" contenteditable="plaintext-only" :placeholder="placeholder" @blur="handleTextBlur"></div>
</template>

<script>
  export default{
    name: 'SkuMark',
    props: {
      value: {
        type: String,
        default: ''
      },
      placeholder: {
        type: String,
        default: '请输入'
      },
      highlightKey: {
        type: Array,
        default: () => []
      },
      pointId: {
        type: String,
        default: 'pointId'
      }
    },
    data(){
      return {}
    },
    watch: {
      value: {
        immediate: true,
        handler(){
          if(!this.value) return;
          this.$nextTick(() => {
            document.getElementById(this.pointId).innerHTML = this.value;
            this.handleTextBlur(this.value);
          })
        }
      }
    },
    methods: {
      handleTextBlur() {
        let val = document.getElementById(this.pointId).innerHTML;
        if(val){
          val = val.replace(new RegExp('<span style="color:red;">', 'g'), '');
          val = val.replace(new RegExp('</span>', 'g'), '');
          this.$emit('input', val);
          this.$emit('change', val);
        }else{
          this.$emit('input', val);
          this.$emit('change', val);
        }

        if(val && this.highlightKey && this.highlightKey.length){
          this.highlightKey.forEach(item => {
            if(val.indexOf(item) > -1){
              let newVal = val.replace(new RegExp(item, 'g'), `<span style="color:red;">${item}</span>`);
              document.getElementById(this.pointId).innerHTML = newVal;
            }
          })
        }
      }
    }
  }
</script>